# 使用pymongo库 读写MongoDB数据库，使用前请确保本地安装了MongoDB数据库
from pymongo import MongoClient


def main():
    # 连接到 MongoDB 服务器，默认是 localhost:27017
    client = MongoClient()
    # 选择或创建一个数据库
    db = client['mongo_db']
    # 选择或创建一个集合
    collection = db['example_collection']
    try:
        # 插入一条数据
        document = {'name': '王昭东', 'age': 200}
        result = collection.insert_one(document)
        print(f"自增长ID: {result.inserted_id}")
        # 插入多条数据
        documents = [
            {'name': '张三', 'age': 30},
            {'name': '李四', 'age': 35}
        ]
        result = collection.insert_many(documents)
        print(f"自增长ID: {result.inserted_ids}")
        # 查找一条数据
        document = collection.find_one({'name': '张三'})
        print(f"找到: {document}")
        # 查找多条数据
        documents = collection.find({'age': {'$gt': 30}})
        for doc in documents:
            print(f"找到: {doc}")
    except Exception as e:
        print(f"数据库错误: {e}")
    finally:
        # 关闭连接
        client.close()


if __name__ == "__main__":
    main()